#!/usr/bin/env node
const commander= require('commander')
const inquirer= require('inquirer')
const fs= require('fs')
const path= require('path')
const vue= require('./vue.json')
const react= require('./react.json')
// 修改文件名称
commander.command('changeName [old] [new]').action((oldName,newName) =>{
    // 1. 判断是否存在  绝对匹配 1：1  模糊匹配1：N
    const isHave = fs.existsSync(oldName)
    if(isHave) {
        // 绝对匹配
        fs.renameSync(oldName,newName)
    } else {
        // 模糊匹配1：N
        const files = fs.readdirSync(__dirname)
        const list = files.filter(item => item.includes(oldName))
        let ind = 0;
        list.forEach(item=>{
            ind+=1
            fs.renameSync(item,`${newName.split('.')[0]}(${ind}).${newName.split('.')[1]}`)
        })
    }
})
// 删除
commander.command('deleteFile [name]').action(name=>{
    const isHave = fs.existsSync(name)
    if(isHave) {
        delFile(__dirname, name)
    } else{
        console.log('没有这个文件')
    }
})
function delFile(dirname, name) {
    const url = path.join(dirname, name);
    const stat=fs.statSync(url)
    if(stat.isFile()) {
        fs.unlinkSync(url)
    } else{
        // 获取目录
        const files = fs.readdirSync(url)
        files.forEach(item => {
            delFile(url, item)
        })
        fs.rmdirSync(url)
    }
}
// 创建脚手架
commander.command('create [projectName]').action(name=>{
    if(fs.existsSync(name)){
        console.log('文件已存在')
    } else {
        inquirer.prompt([
            {
                type: 'list',
                name:"type",
                message:"请选择项目类型",
                choices: ['vue','react']
            }
        ]).then(res=>{
            fs.mkdirSync(name)
            if(res.type==='vue') {
                initProject(name, vue)
            } else {
                initProject(name, react)
            }
        })
    }
})
function initProject(dirname, obj) {
    if(obj.dirname){
        // 文件夹
        const dirUrl = path.join(dirname,obj.dirname)
        fs.mkdirSync(dirUrl)
        if(obj.children) {
            obj.children.forEach(item=>{
                initProject(dirUrl, item) 
            })
        }
    } else {
        // 文件
        fs.writeFileSync(path.join(dirname, obj.filename),'')
    }
}
commander.parse(process.argv)